package com.qijian.tool.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.file.AliyunOSSUtil;
import com.qijian.common.utils.file.FileUtils;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.tool.domain.Storage;
import lombok.SneakyThrows;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpFileUtil {

    @SneakyThrows
    public static Storage getFileByUrlToAliYun(String path, String folder, String fileName) {
        String suffix = fileName.substring(StringUtils.lastIndexOf(fileName, ".") + 1);
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        byte[] data = IoUtil.readBytes(connection.getInputStream());
        long size = data.length;
        String s = AliyunOSSUtil.uploadObject2OSS(AliyunOSSUtil.getOSSClient(), new ByteArrayInputStream(data), folder, String.format("%s.%s", IdUtils.fastSimpleUUID(), suffix));
        connection.disconnect();
        Storage storage = new Storage();
        storage.setName(fileName);
        storage.setRealName(fileName);
        storage.setStorageType(Storage.StorageType.ALIOSS);
        storage.setSize(FileUtils.getSize(size));
        storage.setUrl(s);
        storage.setSuffix(suffix);
        storage.setType(FileUtils.getFileType(storage.getSuffix()));
        return storage;
    }

    @SneakyThrows
    public static byte[] getFileByte(String path) {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        byte[] data = IoUtil.readBytes(connection.getInputStream());
        connection.disconnect();
        return data;
    }

    @SneakyThrows
    public static File downloadFileLocalTempDir(String path) {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        byte[] data = IoUtil.readBytes(connection.getInputStream());
        connection.disconnect();
        return FileUtil.writeBytes(data, FileUtils.SYS_TEM_DIR);
    }
}
